package com.dqyy.order.service.impl;

import com.dqyy.order.service.DatabaseBackupService;
import com.dqyy.order.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Service
public class DatabaseBackupServiceImpl implements DatabaseBackupService {

    @Autowired
    private JavaMailSender mailSender;


    @Value("${spring.datasource.username}")
    private String dbUsername;

    @Value("${spring.datasource.password}")
    private String dbPassword;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${database.backup.email.to}")
    private String toEmail;

    @Value("${database.backup.path}")
    private String backupPath;


    @Override
    public File backupDatabase() {
        try {

            // 创建备份文件名
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String backupFileName = String.format("%s_%s.sql", "order_system", timestamp);
            File backupFile = new File(backupPath, backupFileName);
            
            // 确保备份目录存在
            backupFile.getParentFile().mkdirs();
            
            // 构建mysqldump命令
            String command = String.format(
                "mysqldump -u%s -p%s %s > %s",
                dbUsername,
                dbPassword,
                "order_system",
                backupFile.getAbsolutePath()
            );

            log.info("执行备份命令: {}", command);
            
            // 执行备份命令
            Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", command});
            int exitCode = process.waitFor();
            
            if (exitCode == 0) {
                log.info("数据库备份成功: {}", backupFile.getAbsolutePath());
                return backupFile;
            } else {
                log.error("数据库备份失败，退出码: {}", exitCode);
                return null;
            }
        } catch (IOException | InterruptedException e) {
            log.error("数据库备份异常", e);
            return null;
        }
    }

    @Override
    public boolean sendBackupToEmail(File backupFile) {
        if (backupFile == null || !backupFile.exists()) {
            log.error("备份文件不存在");
            return false;
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            // 设置邮件信息
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject("数据库备份 - " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            
            // 构建邮件内容
            StringBuilder content = new StringBuilder();
            content.append("<h2>数据库备份文件</h2>");
            content.append("<p>备份时间：").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("</p>");
            content.append("<p>文件大小：").append(backupFile.length() / 1024).append(" KB</p>");
            
            helper.setText(content.toString(), true);
            
            // 添加附件
            helper.addAttachment(backupFile.getName(), backupFile);
            
            // 发送邮件
            mailSender.send(message);
            log.info("备份文件发送成功");
            
            // 删除备份文件
            backupFile.delete();
            
            return true;
        } catch (MessagingException e) {
            log.error("发送备份文件失败", e);
            return false;
        }
    }
} 